<template>
  <div class="containers">
    <div class="container">
      <div class="handle-box">
        <el-select v-model="wallet_type" @change="getData" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="(item, index) in wallet_typelist" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-date-picker class="mr10" v-model="value2" type="datetimerange" :picker-options="pickerOptions" style="width: 220px;"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="mini" align="right"
          @change="changeTime">
        </el-date-picker>
        <el-input v-model="keyword" placeholder="关键字/电话/名字" class="handle-input mr10" style="width: 220px;" size="mini"></el-input>

        <el-button type="primary" icon="el-icon-search" @click="getData" class="" size="mini">搜索</el-button>
        <el-button type="primary" @click="exportExcel" class="" size="mini">导出</el-button>
        <el-button @click="showFilterDialog = true" size="mini">
          选择详细类型
          <el-badge :value="detailed.length" :max="99" v-if="detailed.length > 0"></el-badge>
        </el-button>
      </div>


      <el-drawer
        title="选择详细类型"
        :visible.sync="showFilterDialog"
        direction="rtl"
        size="30%"
        :with-header="true">
        <div style="padding: 20px;">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" size="mini">全选
          </el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="detailed" size="mini" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="item in detailedlist" :label="item[0]" :key="item[0]">{{ item[1] }}</el-checkbox>
          </el-checkbox-group>
          <div style="margin-top: 20px;">
            <el-button type="primary" @click="showFilterDialog = false" size="mini">确定</el-button>
            <el-button @click="showFilterDialog = false" size="mini">取消</el-button>
          </div>
        </div>
      </el-drawer>
      <el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header" size="mini" border :height="$tableHight"
        @selection-change="handleSelectionChange" v-loading="loading" id="out-table">
        <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
        <el-table-column prop="user.nickname" label="用户">
          <template slot-scope="scope">
            <div class="ellipsis-cell">{{ scope.row.user.nickname }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="user.mobile" label="用户电话">
          <template slot-scope="scope">
            <div class="ellipsis-cell">{{ scope.row.user.mobile }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="金额">
          <template slot-scope="scope">
            <div class="ellipsis-cell">{{ scope.row.money }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="order" label="订单号">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.order" placement="top" :disabled="!scope.row.order">
              <div class="ellipsis-cell">{{ scope.row.order }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="source.nickname" label="来源用户">
          <template slot-scope="scope">
            <div class="ellipsis-cell">{{ scope.row.source.nickname }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="source.mobile" label="来源用户电话">
          <template slot-scope="scope">
            <div class="ellipsis-cell">{{ scope.row.source.mobile }}</div>
          </template>
        </el-table-column>
        <el-table-column label="钱包类型" align="center">
          <template slot-scope="scope">
            <div class="ellipsis-cell">{{ wallet_typelist[scope.row.wallet_type + 1].name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center">
          <template slot-scope="scope">
            <el-tooltip :content="gettype(scope.row.detailed)" placement="top">
              <div class="ellipsis-cell">{{ gettype(scope.row.detailed) }}</div>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column prop="notes" label="备注">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.notes" placement="top" :disabled="!scope.row.notes">
              <div class="ellipsis-cell">{{ scope.row.notes }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="时间" align="center" width="160">
          <template slot-scope="scope">
            <el-tooltip :content="$clearTimer(scope.row.CreatedAt)" placement="top">
              <div class="ellipsis-cell">{{ $clearTimer(scope.row.CreatedAt) }}</div>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>
      <!-- <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange" :current-page="query.pageIndex"
          :page-sizes="[20, 30, 40, 50]" :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal">
        </el-pagination>
      </div> -->
      <div class="bt" style="margin-top: 20px;">
        <el-button type="primary" @click="prevclick" size="mini">上一页</el-button>
        <el-button type="primary" @click="nextclick" size="mini">下一页</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  name: 'basetable',
  data() {
    return {
      totalMoney: 0,
      showFilterDialog: false,

      query: {
        pageIndex: 1,
        pageSize: 15
      },
      isPage: false,
      tableData: [],
      pageTotal: 0,
      keyword: '',//搜索关键字/电话/名字
      loading: false,
      detailed: [],//detailed类型
      detailedlist: [],//detailed类型

      checkAll: false,
      isIndeterminate: true,
      wallet_type: -1,//余额类型
      wallet_typelist: [{ name: "全部", id: -1 }, { name: "消费券", id: 0 }, { name: "补贴卷", id: 1 }, { name: "资产积分", id: 2 }, { name: "绿色积分", id: 3 }],
      walletList: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      value2: '',
      start_time: '',
      end_time: '',
      queryParameters: {} // 添加用于存储所有查询参数的数据属性
    };
  },
  created() {
    try {
      this.keyword = this.$route.query.mobile ? this.$route.query.mobile : ''
    } catch (error) {

    }

    // 获取所有查询参数并存储在queryParameters中
    this.queryParameters = { ...this.$route.query };
    console.log('页面路径上的参数:', this.queryParameters);
    this.wallet_type = this.queryParameters.value ? Number(this.queryParameters.type) : -1

    // 如果路径上有参数，则自动设置今天的日期
    if (Object.keys(this.queryParameters).length > 0) {
      this.$nextTick(() => {
        this.setTodayDate();
      });
    }

    this.load()
  },
  methods: {
    // 设置今天的日期
    setTodayDate() {
      const today = new Date();
      const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
      const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);

      this.value2 = [startOfDay, endOfDay];
      this.start_time = this.formatDate(startOfDay);
      this.end_time = this.formatDate(endOfDay);
      // 触发时间改变事件以更新数据
      this.changeTime(this.value2);
    },

    prevclick() {
      let val = this.query.pageIndex - 1
      console.log(val)
      if (val <= 0) {
        return;
      }
      this.$set(this.query, 'pageIndex', val);
      this.getData()
    },
    nextclick() {
      console.log(this.isPage)
      if (this.isPage) {
        return;
      }

      let val = this.query.pageIndex + 1
      console.log(val)
      this.$set(this.query, 'pageIndex', val);
      this.getData()
    },
    exportExcel() {//导出
      var xlsxParam = { raw: true };//转换成excel时，使用原始的格式
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"), xlsxParam);
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
          "钱包记录.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    load() {
      let that = this
      this.request('business/getWallet/', 'get').then(
        res => {
          this.walletList = res.data.wallet
          let list = res.data.wallet


          for (const i in list) {
            that.detailedlist.push([list[i].detailed, list[i].detaileds])
          }
          if(this.queryParameters.value) {
            this.detailed.push(Number(this.queryParameters.value))
          }else{
            for (let i in list) {
              that.detailed.push(list[i].detailed)

            }
          }

          this.getData()
        },
        function () {
          console.log('请求失败处理');
        }
      );
    },
    gettype(detailed) {
      let str = ""
      this.walletList
      for (let i in this.walletList) {
        if (this.walletList[i].detailed == detailed) {
          return this.walletList[i].detaileds
        }
      }
    },
    handleCheckAllChange(val) {//全选
      this.detailed = [];
      if (val) {
        this.detailedlist.forEach(f => {
          this.detailed.push(f[0]);
        });
      }
      this.isIndeterminate = false;
      this.getData()
    },
    handleCheckedCitiesChange(value) {//多选变化
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.detailedlist.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.detailedlist.length;
      this.query.pageIndex = 1;
      this.getData()
    },
    //修改size值
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.query.pageSize = val
      this.getData();
    },

    //获取数据
    getData() {
      // this.tableData=[]
      this.loading = true
      this.request('business/businessRecords/', 'get',
        { start_time: this.start_time, end_time: this.end_time, page: this.query.pageIndex, size: this.query.pageSize, keyword: this.keyword, wallet_type: this.wallet_type, detailed: JSON.stringify(this.detailed) }
      ).then(res => {
        this.tableData = res.data.data
        // this.pageTotal = res.data.total
        this.totalMoney = res.data.totalMoney

        this.loading = false
        if (this.tableData.length < 15) {
          this.isPage = true
        }
      })
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, 'pageIndex', val);
      this.getData();
    },
    changeTime(e) {//时间
      try {
        this.start_time = this.formatDate(e[0])
        this.end_time = this.formatDate(e[1])
      } catch (error) {
        this.start_time = ''
        this.end_time = ''
      }
      this.getData()
    },
    formatTen(num) {
      return num > 9 ? (num + "") : ("0" + num);
    },
    formatDate(date) {
      var date = new Date(date)
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();
      return year + "-" + this.formatTen(month) + "-" + this.formatTen(day) + " " + this.formatTen(hour) + ":" + this.formatTen(minute) + ":" + this.formatTen(second);
    }
  }
};
</script>

<style scoped>
/* 使用 /deep/ 或 >>> 来穿透 scoped 样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #f2f2f2;
  /* 设置表头颜色 */
  color: #333;
  /* 设置表头文字颜色 */
}
.bt {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
}

.container {
  padding: 20px;
}

.el-upload--text {
  width: 200px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;

  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  /* width: 100px; */
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 178px;
  display: block;
}

.handle-box {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.ellipsis-cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 60px;
  height: 60px;

  .el-image img {
    object-fit: cover;
  }
}

/* 设置分页按钮样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
